package com.ort.ezcalendar.rest;

import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Properties;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicHeader;
import org.apache.http.protocol.HTTP;
import org.apache.http.util.EntityUtils;
import org.json.JSONArray;
import org.json.JSONObject;

import android.app.ProgressDialog;
import android.content.Context;
import android.content.res.AssetManager;
import android.content.res.Resources;
import android.content.res.Resources.NotFoundException;
import android.database.Cursor;
import android.os.AsyncTask;
import android.util.Log;

import com.ort.ezcalendar.Event;
import com.ort.ezcalendar.persistance.EventHelper;

public class SynchronizeTask extends AsyncTask<String, Void, Boolean> {
	private ProgressDialog dialog;
	private EventHelper helper;
	protected Context applicationContext;
	private Cursor model;

	public SynchronizeTask(Context c) {
		applicationContext = c;
		helper = new EventHelper(c);
		dialog = new ProgressDialog(applicationContext);
	}

	@Override
	protected void onPreExecute() {

		this.dialog = ProgressDialog.show(applicationContext,
				"Validando usuario", "........", true);
	}

	@Override
	protected Boolean doInBackground(String... params) {
		try {
			String urlConection = "http://192.168.2.4/EzCalendar/ServiceEzCalendar.svc/SinchronyzeEvents/"
					+ params[0] + "/" + params[1];
//			" + readProperties("connection") + readProperties("synchronize")
			DefaultHttpClient httpClient = new DefaultHttpClient();
			HttpPost httpPost = new HttpPost(urlConection);
			httpPost.setHeader("Content-type", "application/json");
			
			JSONArray jsonArray = new JSONArray();
			model = helper.getAllEvents();
			List<Event> eventList = new ArrayList<Event>();
			model.moveToFirst();
			while (!model.isAfterLast()) {
				Event e = new Event();
				JSONObject jsonObject = new JSONObject();
				jsonObject.put("Alarms",helper.getAllAlarms(helper.getId(model)));
				
				jsonObject.put("Category",helper.getCategory(model));
				jsonObject.put("DateEvent",String.valueOf(helper.getDate(model).getTime()));
				jsonObject.put("Description",helper.getDescription(model));
				jsonObject.put("Latitute",helper.getLatitude(model));
				jsonObject.put("Longitude",helper.getLongitude(model));
				jsonObject.put("Name",helper.getName(model));
				jsonObject.put("Place",helper.getPlace(model));
				jsonArray.put(jsonObject);
				model.moveToNext();
			}
			model.close();
			
			StringEntity se = new StringEntity(jsonArray.toString());
			se.setContentEncoding(new BasicHeader(HTTP.CONTENT_TYPE,
					"application/json"));
			httpPost.setEntity(se);

			HttpResponse httpResponse = httpClient.execute(httpPost);

			HttpEntity httpEntity = httpResponse.getEntity();
	        String respStr = EntityUtils.toString(httpEntity);
			 
	        if(respStr.equals("true")) {
				return true;
			}
			return false;
		} catch (NotFoundException e) {
			Log.e("Error", e.toString());
			return false;
		} catch (Exception e) {
			Log.e("Error", e.toString());
			return false;
		}
	}

	@Override
	protected void onPostExecute(Boolean result) {
		this.dialog.cancel();
		helper.close();
	}
	
	private String readProperties(String key) throws IOException {
		String value = "";
		try {
			Resources resources = applicationContext.getResources();
			AssetManager assetManager = resources.getAssets();
			InputStream inputStream = null;
			inputStream = assetManager.open("conection.properties");
			Properties properties = new Properties();
			properties.load(inputStream);
			value = properties.getProperty(key);
		} catch (IOException e) {
			e.printStackTrace();
		}
		return value;
	}

}
